<template>
	<view>
		<view class="search-box">
			<uni-search-bar @input="input" :radius="100" cancelButton="none"></uni-search-bar>
		</view>
		
		<!-- 搜索建议列表 -->
		<view class="sugg-list" v-if="searchResults.length !== 0">
			<view class="sugg-item" v-for="(item,index) in searchResults" :key="index" @click="gotoDetail(item)">
				<view class="goods-name">{{item.goods_name}}</view>
				<uni-icons type="right" size="16"></uni-icons>
			</view>
		</view>
		
		
		<!-- 搜索历史 -->
		<view class="history-box" v-else>
			<!-- 标题区域 -->
			<view class="history-title">
				<text>搜索历史</text>
				<uni-icons type="trash" size="18" @click="clean"></uni-icons>
			</view>
			<!-- 列表区域 -->
			<view class="history-list">
				<uni-tag :text="item2" v-for="(item2,index2) in historyies" :key="index2" @click="gotoGoodsList(item2)"></uni-tag>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				timer:null,
				kw:'',
				searchResults:[],
				// 搜索历史数组
				historyList:[]
			};
		},
		onLoad() {
			this.historyList = JSON.parse(uni.getStorageSync('kw') || '[]')
		},
		computed:{
			// 注意卧槽 再搜索历史前面添加
			historyies(){
				return [...this.historyList].reverse()
			}
		},
		methods:{
			gotoGoodsList(kw){
				uni.navigateTo({
					url:'/subpkg/goods_list/goods_list?query=' + kw
				})
			},
			// 清空历史记录
			clean(){
					this.historyList = []
					uni.setStorageSync('kw','[]')
			},
			input(e){
				clearTimeout(this.timer)
				// console.log(e)
				this.timer = setTimeout(()=>{
				this.kw = e
				this.getSearchList()
				},500)
			},
			async getSearchList(){
				if(this.kw.length === 0){
					this.searchResults = []
					return
				}
			
				const {data:res} = await uni.$http.get('api/public/v1/goods/qsearch',{query:this.kw})
				if(res.meta.status !== 200 ) return uni.$showMsg()
				this.searchResults = res.message
				
				this.saveSearchHistory()
			},
		// 跳转商品详情页
			gotoDetail(item){
				uni.navigateTo({
					url:'/subpkg/goods_detail/goods_detail?goods_id=' + item.goods_id
				})
			},
		// 搜索历史添加
			saveSearchHistory(){
				// this.historyList.push(this.kw)
				const set = new Set(this.historyList)
				// 先移除旧元素
				set.delete(this.kw)
				// 再添加
				set.add(this.kw)
				// 再转化成一个数组 存到historyList里面
				this.historyList = Array.from(set)
				// 持久化
				uni.setStorageSync('kw',JSON.stringify(this.historyList))
			},
	}
}
</script>
<style lang="scss">
// 搜索栏固定吸附
// 搜索建议列表css
// 搜索历史css
</style>
